document.addEventListener('DOMContentLoaded', function() {
    var playPauseButton = document.querySelector('.play-pause-btn');
    var speedControlButton = document.querySelector('.speed-control-btn');
    var progressBar = document.querySelector('.progress-bar');
    var container = document.querySelector('#container');
    var utterance = null;

    // 初始化语音合成
    if ('speechSynthesis' in window) {
        // 获取正文内容
        var contentText = container.innerText || container.textContent;

        // 创建一个新的SpeechSynthesisUtterance对象
        utterance = new SpeechSynthesisUtterance(contentText);

        // 设置默认语速
        utterance.rate = 1;

        // 监听播放状态改变事件以更新进度条
        utterance.onboundary = function(event) {
            // 更新进度条宽度
            var percentComplete = (event.charIndex / utterance.text.length) * 100;
            progressBar.style.width = percentComplete + "%";
        };

        // 播放/暂停功能
        playPauseButton.addEventListener('click', function() {
            if (speechSynthesis.speaking && !speechSynthesis.paused) {
                speechSynthesis.pause();
                this.textContent = "播放";
            } else if (speechSynthesis.paused) {
                speechSynthesis.resume();
                this.textContent = "暂停";
            } else {
                speechSynthesis.speak(utterance);
                this.textContent = "暂停";
            }
        });

        // 调整语速功能
        speedSelect.addEventListener('change', function() {
            utterance.rate = parseFloat(this.value);
            if (!speechSynthesis.paused) {
                speechSynthesis.cancel();
                speechSynthesis.speak(utterance);
            }
        });
        
        // 当结束朗读时重置按钮文字
        utterance.onend = function() {
            playPauseButton.textContent = "播放";
            progressBar.style.width = "0%";
        };
    } else {
        playPauseButton.disabled = true;
        alert('您的浏览器不支持文本转语音功能。');
    }

    // 提示信息
    playPauseButton.title = "需要Web Speech API支持";
});